﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team (cellcloudproject@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellFileExpressContext.h"
#include "CellSingleFileStorage.h"
#include "CellResultSet.h"
#include "CellFileUtil.h"
#include "CellUtil.h"
#include "CellDate.h"
#include "CellCryptologyImpl.h"

namespace cell
{
//---------------------------------------------------------------------------
FileExpressContext::FileExpressContext(const ExpressAuthCode& authCode)
	: mOperate(FileExpressContext::OP_SERVO)
	, mAuthCode(authCode)
	, mAttribute(NULL)
	, mErrorCode(EC_SUCCESS)
	, mBytesLoaded(0)
	, mBytesTotal(0)
{
	FileUtil::createDirectory(mAuthCode.getContextPath());
}
//---------------------------------------------------------------------------
FileExpressContext::FileExpressContext(const String& authCode
	, const InetAddress* address, const String& fullPath)
	: mOperate(FileExpressContext::OP_UPLOAD)
	, mFullPath(fullPath)
	, mAttribute(NULL)
	, mErrorCode(EC_SUCCESS)
	, mBytesLoaded(0)
	, mBytesTotal(0)
{
	mAuthCode.setCode(authCode);

	FileUtil::splitFullPath(mFullPath, mFileName, mPath);

	if (address->isIPv4())
	{
		mAddress.setHostAddress(address->getHostAddress());
		mAddress.setPort(address->getPort());
	}

	mAttribute = CELL_NEW FileAttribute();
}
//---------------------------------------------------------------------------
FileExpressContext::FileExpressContext(const String& authCode
	, const InetAddress* address, const String& fileName, const String& path)
	: mOperate(FileExpressContext::OP_DOWNLOAD)
	, mFileName(fileName)
	, mPath(path)
	, mAttribute(NULL)
	, mErrorCode(EC_SUCCESS)
	, mBytesLoaded(0)
	, mBytesTotal(0)
{
	mAuthCode.setCode(authCode);

	mFullPath = path + fileName;

	if (address->isIPv4())
	{
		mAddress.setHostAddress(address->getHostAddress());
		mAddress.setPort(address->getPort());
	}

	mAttribute = CELL_NEW FileAttribute();
}
//---------------------------------------------------------------------------
FileExpressContext::~FileExpressContext(void)
{
	if (NULL != mAttribute)
	{
		CELL_DELETE mAttribute;
		mAttribute = NULL;
	}
}
//---------------------------------------------------------------------------
const ExpressAuthCode* FileExpressContext::getAuthCode(void) const
{
	return &mAuthCode;
}
//---------------------------------------------------------------------------
FORCEINLINE uint FileExpressContext::getOperate(void) const
{
	return mOperate;
}
//---------------------------------------------------------------------------
inline const InetAddress* FileExpressContext::getAddress(void) const
{
	return &mAddress;
}
//---------------------------------------------------------------------------
const String& FileExpressContext::getFullPath(void) const
{
	return mFullPath;
}
//---------------------------------------------------------------------------
const String& FileExpressContext::getFileName(void) const
{
	return mFileName;
}
//---------------------------------------------------------------------------
FileAttribute* FileExpressContext::getAttribute(void) const
{
	return mAttribute;
}
//---------------------------------------------------------------------------
inline int FileExpressContext::getErrorCode(void) const
{
	return mErrorCode;
}
//---------------------------------------------------------------------------
inline long FileExpressContext::getBytesLoaded(void) const
{
	return mBytesLoaded;
}
//---------------------------------------------------------------------------
inline long FileExpressContext::getBytesTotal(void) const
{
	return mBytesTotal;
}
//---------------------------------------------------------------------------
void FileExpressContext::setErrorCode(int code)
{
	mErrorCode = code;
}
//---------------------------------------------------------------------------
inline void FileExpressContext::setBytesLoaded(long bytes)
{
	mBytesLoaded = bytes;
}
//---------------------------------------------------------------------------
void FileExpressContext::setBytesTotal(long bytes)
{
	mBytesTotal = bytes;
}
//---------------------------------------------------------------------------
void FileExpressContext::reset(const String& fileName, const String& path, const FileAttribute* attr)
{
	mFileName = fileName;
	mPath = path;
	mFullPath = mPath + mFileName;

	if (NULL == mAttribute)
	{
		mAttribute = CELL_NEW FileAttribute();
	}

	*mAttribute = *attr;
}
//---------------------------------------------------------------------------
void FileExpressContext::resetFileSize(long size)
{
	if (NULL != mAttribute)
	{
		mAttribute->size(size);
	}
}



//---------------------------------------------------------------------------
FileExpressServoContext::FileExpressServoContext(const ExpressAuthCode& authCode)
	: FileExpressContext(authCode)
{
	mTimestamp = Util::currentTimeMillis();
}
//---------------------------------------------------------------------------
FileExpressServoContext::~FileExpressServoContext(void)
{
	CELL_LOCK_MUTEX(mMutex);

	FileAttributes::iterator fait = mAttributes.begin(), fae = mAttributes.end();
	while (fait != fae)
	{
		CELL_DELETE fait->second;
		++fait;
	}

	Storages::iterator sit = mStorages.begin(), se = mStorages.end();
	while (sit != se)
	{
		ReadResultSets::iterator rit = mReadResultSets.find(sit->first);
		if (rit != mReadResultSets.end())
		{
			sit->second->destroyResultSet(rit->second);
			mReadResultSets.erase(rit);
		}

		sit->second->close();

		CELL_DELETE sit->second;
		++sit;
	}

	Contexts::iterator cit = mContexts.begin(), ce = mContexts.end();
	while (cit != ce)
	{
		CELL_DELETE cit->second;
		++cit;
	}
}
//---------------------------------------------------------------------------
FileAttribute* FileExpressServoContext::getAttribute(const String& fileName) const
{
	CELL_LOCK_MUTEX(mMutex);

	FileAttributes::const_iterator iter = mAttributes.find(fileName);
	if (iter != mAttributes.end())
	{
		return iter->second;
	}

	return NULL;
}
//---------------------------------------------------------------------------
FileExpressContext* FileExpressServoContext::getContext(const String& fileName)
{
	CELL_LOCK_MUTEX(mMutex);

	Contexts::iterator iter = mContexts.find(fileName);
	if (iter != mContexts.end())
	{
		return iter->second;
	}

	return NULL;
}
//---------------------------------------------------------------------------
void FileExpressServoContext::loadFile(const String& fileName)
{
	CELL_LOCK_MUTEX(mMutex);

	Storages::iterator iter = mStorages.find(fileName);
	if (iter != mStorages.end())
	{
		return;
	}

	SingleFileStorage* storage = CELL_NEW SingleFileStorage(fileName);
	mStorages.insert(Storages::value_type(fileName, storage));

	FileExpressContext* context = CELL_NEW FileExpressContext(mAuthCode);
	mContexts.insert(Contexts::value_type(fileName, context));

	// 创建文件属性
	FileAttribute* attr = CELL_NEW FileAttribute();
	mAttributes.insert(FileAttributes::value_type(fileName, attr));

	// 打开存储
	storage->open(mAuthCode.getContextPath() + fileName);

	// 查询文件
	ResultSet* rs = storage->createResultSet();
	storage->store(rs, storage->getReadStatement());

	// 定位
	rs->next();

	// 文件是否存在
	if (rs->getBool(SingleFileStorage::FIELD_EXIST))
	{
		// 文件存在
		attr->exist(true);

		// 文件大小
		attr->size(rs->getLong(SingleFileStorage::FIELD_SIZE));

		// 最后修改时间
		std::time_t time = FileUtil::lastModifyTime(mAuthCode.getContextPath() + fileName);
		attr->lastModifyTime(Date::convertTimeToDate(*localtime(&time)));

		// 文件小于 1MB (1048576 bytes) 计算 MD5 码
		if (attr->size() <= 1048576)
		{
			// 获取加密工具实例
			Cryptology* crypt = Cryptology::getSingletonPtr();
			int sn = crypt->beginHash(Cryptology::MD5);
			if (sn > 0)
			{
				int offset = 0;
				int len = 0;
				char buf[8192] = {0x0};
				byte cryptInput[8192] = {0x0};
				while ((len = rs->getRaw(SingleFileStorage::FIELD_DATA, buf, offset, sizeof(buf))) > 0)
				{
					memcpy(cryptInput, buf, len);
					crypt->updateHash(sn, cryptInput, len);

					offset += len;
				}

				byte out[32] = {0x0};
				int rlen = crypt->endHash(out, sn);
				String hashCode = Cryptology::bytesToString(out, rlen);

				// MD5 码
				attr->hashCode(hashCode);
			}
		}
	}
	else
	{
		attr->exist(false);
	}

	// 设置上下文数据
	context->reset(fileName, mAuthCode.getContextPath(), attr);

	storage->destroyResultSet(rs);
}
//---------------------------------------------------------------------------
int FileExpressServoContext::readFile(char* data, const String& fileName, int64 offset, int length)
{
	CELL_LOCK_MUTEX(mMutex);

	ResultSet* resultSet = NULL;
	ReadResultSets::iterator iter = mReadResultSets.find(fileName);
	if (iter != mReadResultSets.end())
	{
		resultSet = iter->second;
	}
	else
	{
		SingleFileStorage* storage = findOpenedStorage(fileName);
		resultSet = storage->createResultSet();
		storage->store(resultSet, storage->getReadStatement());
		resultSet->next();

		mReadResultSets.insert(ReadResultSets::value_type(fileName, resultSet));
	}

	int len = resultSet->getRaw(SingleFileStorage::FIELD_DATA, data, offset, (int64)length);
	return len;
}
//---------------------------------------------------------------------------
void FileExpressServoContext::prepareFile(const String& fileName, long fileSize)
{
	CELL_LOCK_MUTEX(mMutex);

	if (!mContexts.empty())
	{
		Contexts::iterator iter = mContexts.find(fileName);
		if (iter != mContexts.end())
		{
			iter->second->resetFileSize(fileSize);
		}
	}

	SingleFileStorage* storage = findOpenedStorage(fileName);

	// 创建结果集
	ResultSet* rs = storage->createResultSet();
	storage->store(rs, storage->getWriteStatement());

	// 移动游标
	rs->next();

	// 更新文件长度
	rs->updateLong(SingleFileStorage::FIELD_SIZE, fileSize);

	// 销毁结果集
	storage->destroyResultSet(rs);
}
//---------------------------------------------------------------------------
void FileExpressServoContext::writeFile(const String& fileName, char* data, int64 offset, int length)
{
	CELL_LOCK_MUTEX(mMutex);

	SingleFileStorage* storage = findOpenedStorage(fileName);

	// 创建结果集
	ResultSet* rs = storage->createResultSet();
	storage->store(rs, storage->getWriteStatement());

	// 移动游标
	rs->next();

	// 写入数据
	rs->updateRaw(SingleFileStorage::FIELD_DATA, data, offset, (int64)length);

	// 销毁结果集
	storage->destroyResultSet(rs);
}
//---------------------------------------------------------------------------
void FileExpressServoContext::closeFile(const String& fileName)
{
	CELL_LOCK_MUTEX(mMutex);

	ResultSet* resultSet = NULL;
	ReadResultSets::iterator rsit = mReadResultSets.find(fileName);
	if (rsit != mReadResultSets.end())
	{
		resultSet = rsit->second;
		mReadResultSets.erase(rsit);
	}

	Storages::iterator iter = mStorages.find(fileName);
	if (iter != mStorages.end())
	{
		SingleFileStorage* storage = iter->second;
		if (resultSet != NULL)
		{
			storage->destroyResultSet(resultSet);
		}

		storage->close();

		mStorages.erase(iter);

		CELL_DELETE storage;
	}
}
//---------------------------------------------------------------------------
int64 FileExpressServoContext::getRemainingTime(void) const
{
	if (ExpressAuthCode::DURATION_NONE == mAuthCode.getDuration())
	{
		// 返回大于 0 的数表示该上下文继续有效
		return 1;
	}

	return (mAuthCode.getDuration() - (Util::currentTimeMillis() - mTimestamp));
}
//---------------------------------------------------------------------------
SingleFileStorage* FileExpressServoContext::findOpenedStorage(const String& fileName)
{
	SingleFileStorage* storage = NULL;

	Storages::iterator iter = mStorages.find(fileName);
	if (iter == mStorages.end())
	{
		storage = CELL_NEW SingleFileStorage(fileName);

		// 打开存储
		storage->open(mAuthCode.getContextPath() + fileName);

		mStorages.insert(Storages::value_type(fileName, storage));
	}
	else
	{
		storage = iter->second;
	}

	return storage;
}

} // end namespace cell
